﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SheepCommon.API.Seedweanings;

namespace SheepCommon.API.BreedingHistoryss
{
    public class BreedingHistorysSearchHander : IRequestHandler<BreedingHistorysSearchCommand, ResultPage<BreedingHistorys>>
    {
        private readonly IBaseRepository<BreedingHistorys> _breedingHistorysRepository;
        private readonly IMapper _mapper;

        public BreedingHistorysSearchHander(IBaseRepository<BreedingHistorys> breedingHistorysRepository, IMapper mapper)
        {
            _breedingHistorysRepository = breedingHistorysRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 查询种母历史
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<BreedingHistorys>> Handle(BreedingHistorysSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<BreedingHistorys>() { Code = (int)CommonErrorCode.Search, TotalCount = 0, PagedCount = 0 };
            try
            {
                var seedweanings = await(await _breedingHistorysRepository.GetAll()).ToListAsync();
                if (request.DateBreeding != null)
                {
                    seedweanings = seedweanings.Where(p => p.DateBreeding == request.DateBreeding).ToList();
                }
                if (!string.IsNullOrEmpty(request.BreedingEarBugle))
                {
                    seedweanings = seedweanings.Where(p => p.BreedingEarBugle == request.BreedingEarBugle).ToList();
                }
             
                result.TotalCount = seedweanings.Count;
                result.PagedCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                seedweanings = seedweanings.OrderByDescending(c => c.BreedingHistoryId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = seedweanings;
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
    }
}
